package com.videoanalysis;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 视频分析结果的数据类
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AnalysisResult {
    /**
     * 视频文件名
     */
    private String videoFileName;

    /**
     * 分析结果目录
     */
    private String resultDirectory;

    /**
     * 提取的关键帧数量
     */
    private int frameCount;

    /**
     * 每个帧的识别结果
     */
    private Map<Path, List<RecognitionResult>> recognitionResults;

    /**
     * 分析时间
     */
    private LocalDateTime analysisTime = LocalDateTime.now();

    /**
     * 获取所有识别到的对象及其出现频率
     * @return 对象及其频率的映射
     */
    public Map<String, Integer> getObjectFrequency() {
        Map<String, Integer> frequency = new HashMap<>();

        recognitionResults.values().forEach(results -> {
            results.forEach(result -> {
                if (result.getProbability() > 0.5) { // 只考虑置信度大于50%的结果
                    frequency.put(result.getClassName(),
                            frequency.getOrDefault(result.getClassName(), 0) + 1);
                }
            });
        });

        return frequency;
    }

    /**
     * 获取视频中最常出现的对象（前N个）
     * @param topN 要返回的对象数量
     * @return 最常出现的对象列表
     */
    public List<Map.Entry<String, Integer>> getTopObjects(int topN) {
        Map<String, Integer> frequency = getObjectFrequency();

        return frequency.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .limit(topN)
                .collect(Collectors.toList());
    }

    /**
     * 将分析结果保存到JSON文件
     * @param outputPath 输出文件路径
     * @throws IOException 如果保存失败
     */
    public void saveToFile(Path outputPath) throws IOException {
        // 创建一个可序列化的结果对象
        Map<String, Object> serializableResult = new HashMap<>();
        serializableResult.put("videoFileName", videoFileName);
        serializableResult.put("resultDirectory", resultDirectory);
        serializableResult.put("frameCount", frameCount);
        serializableResult.put("analysisTime", analysisTime.toString());

        // 转换识别结果为可序列化格式
        Map<String, List<Map<String, Object>>> serializableRecognitionResults = new HashMap<>();
        recognitionResults.forEach((path, results) -> {
            List<Map<String, Object>> serializableResults = results.stream()
                    .map(r -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("className", r.getClassName());
                        map.put("probability", r.getProbability());
                        return map;
                    })
                    .collect(Collectors.toList());

            serializableRecognitionResults.put(path.getFileName().toString(), serializableResults);
        });
        serializableResult.put("recognitionResults", serializableRecognitionResults);

        // 添加频率统计
        serializableResult.put("objectFrequency", getObjectFrequency());
        serializableResult.put("topObjects", getTopObjects(10));

        // 写入JSON文件
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.writeValue(outputPath.toFile(), serializableResult);
    }

    /**
     * 生成分析结果的摘要
     * @return 分析结果摘要
     */
    public String generateSummary() {
        StringBuilder summary = new StringBuilder();
        summary.append("视频分析摘要\n");
        summary.append("=================\n\n");
        summary.append("视频文件: ").append(videoFileName).append("\n");
        summary.append("分析时间: ").append(analysisTime).append("\n");
        summary.append("提取关键帧数: ").append(frameCount).append("\n\n");

        summary.append("视频中最常出现的对象:\n");
        getTopObjects(5).forEach(entry -> {
            summary.append("- ").append(entry.getKey())
                   .append(": ").append(entry.getValue())
                   .append(" 帧\n");
        });

        return summary.toString();
    }
}
